package com.szewec.ps.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.szewec.ps.R;
import com.szewec.ps.base.BaseTitleBar;
import com.szewec.ps.base.CommonDialog;
import com.szewec.ps.base.Constants;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.myinterface.BindEditTextViewValue;
import com.szewec.ps.myinterface.CallBackInterface;
import com.szewec.ps.myview.BaseInput;

import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

import razerdp.basepopup.QuickPopupBuilder;
import razerdp.basepopup.QuickPopupConfig;

public class CommonUtils {
    /**
     * 检查是否有网络
     */
    public static boolean isNetworkAvailable(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        if (info != null) {
            return info.isAvailable();
        }
        return false;
    }

    /**
     * 检查是否是WIFI
     */
    public static boolean isWifi(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        if (info != null) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI)
                return true;
        }
        return false;
    }

    /**
     * 检查是否是移动网络
     */
    public static boolean isMobile(Context context) {
        NetworkInfo info = getNetworkInfo(context);
        if (info != null) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE)
                return true;
        }
        return false;
    }

    private static NetworkInfo getNetworkInfo(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    /**
     * 检查SD卡是否存在
     */
    public static boolean checkSdCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    /**
     * 弹出对话框, 跳转定位设置页面
     *
     * @param activity
     */
    public static void openLocationSetting(Activity activity, String hintContent) {
        CommonDialog dialog = new CommonDialog(activity);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setTitle("提示");
        dialog.setContent(hintContent);
        dialog.setEnsure("去设置");
        dialog.setOnEnsureClickListener(view -> {
            // 点击"确认"后的操作
            dialog.dismiss();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            activity.startActivityForResult(intent, Constants.REQUEST_CODE.LOCATION);
        });
        dialog.setOnCancelClickListener(view -> {
            // 点击"取消"后的操作
            dialog.dismiss();
            activity.finish();
        });
        dialog.show();
    }

    /**
     * 生成随机ID
     *
     * @return
     */
    public static String generateId() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /**
     * 根据词典的值获取对应的key
     *
     * @return
     */
    public static Integer getDictKey(List list, String value) {
        if (list != null && list.size() > 0 && !"".equals(value)) {
            int key = list.indexOf(value);
            return key < 0 ? null : key;
        } else {
            return null;
        }
    }

    /**
     * 根据词典的值获取对应的key，当库存放下标从1开始，请使用该方法
     *
     * @return
     */
    public static Integer getDictKeyForOne(List list, String value) {
        if (list != null && list.size() > 0 && !"".equals(value)) {
            int key = list.indexOf(value);
            return key < 0 ? null : key + 1;
        } else {
            return null;
        }
    }

    /**
     * 根据对应的key获取词典的值
     *
     * @return
     */
    public static String getDictValue(List list, Integer key) {
        if (key != null && key < list.size()) {
            return (String) list.get(key);
        } else {
            return "";
        }
    }

    /**
     * 弹出双按钮弹框
     */
    public static void doubleBtnDialog(Context context, CallBackInterface callBackInterface) {
        final CommonDialog commonDialog = new CommonDialog(context);
        commonDialog.setTitle(context.getResources().getString(R.string.confirm_hint));
        commonDialog.setContent(context.getResources().getString(R.string.delete_hint));
        commonDialog.setOnEnsureClickListener(view -> {
            commonDialog.dismiss();
            callBackInterface.customizedFun();
        });
        commonDialog.setOnCancelClickListener(view -> commonDialog.dismiss());
        commonDialog.show();
    }

    /**
     * 展示menu方法
     */
    public static void showMoreMenu(Context context, RelativeLayout layout, CallBackInterface callBackInterface1, CallBackInterface callBackInterface2) {
        QuickPopupBuilder.with(context)
                .contentView(R.layout.popup_menu_more_standard)
                .config(new QuickPopupConfig()
                        .clipChildren(true)
                        .gravity(Gravity.BOTTOM | Gravity.START)
                        .offsetX(ConvertDpAndPx.Dp2Px(context, 43.5f))
                        .offsetY(ConvertDpAndPx.Dp2Px(context, -5f))
                        .backgroundColor(context.getResources().getColor(R.color.C1A000000))
                        .withClick(R.id.tx_1, view -> callBackInterface1.customizedFun(), true)
                        .withClick(R.id.tx_2, view -> CommonUtils.doubleBtnDialog(context, callBackInterface2), true)
                ).show(layout);
    }

    /**
     * 设置页面中输入框的模式
     */
    public static void switchMode(LinearLayout linearLayout, boolean isEnabled) {
        if (linearLayout != null) {
            for (int i = 0; i < linearLayout.getChildCount(); i++) {
                View view = linearLayout.getChildAt(i);
                if (view instanceof BaseInput) {
                    ((BaseInput) view).switchoverMode(isEnabled);
                }
            }
        }
    }

    /**
     * 初始化新增, 查看, 修改等页面
     *
     * @param viewModeValue
     * @param callBackInterface1
     * @param callBackInterface2
     */
    public static void setViewMode(ViewModeValue viewModeValue, CallBackInterface callBackInterface1, CallBackInterface callBackInterface2) {
        Context context = viewModeValue.getContext();
        String mode = viewModeValue.getMode();
        BaseTitleBar baseTitleBar = viewModeValue.getBaseTitleBar();
        LinearLayout linearLayout = viewModeValue.getLinearLayout();

        baseTitleBar.setLeftLayoutVisibility(View.VISIBLE);
        baseTitleBar.setRightLayoutVisibility(View.VISIBLE);
        if (Constants.PRESENT_VALUE_FLAG.ADD.equals(mode) || Constants.PRESENT_VALUE_FLAG.EDIT.equals(mode)) {
            baseTitleBar.setRightImageVisibility(View.GONE);
            baseTitleBar.setRightTextVisibility(View.VISIBLE);
            baseTitleBar.setRightText(context.getResources().getString(R.string.save));
            CommonUtils.switchMode(linearLayout, true);
        } else if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(mode)) {
            baseTitleBar.setRightImageVisibility(View.GONE);
            baseTitleBar.setRightTextVisibility(View.VISIBLE);
            baseTitleBar.setRightText(context.getResources().getString(R.string.edit));
            CommonUtils.switchMode(linearLayout, false);
        } else if (Constants.PRESENT_VALUE_FLAG.VIEW_ONE.equals(mode)) {
            baseTitleBar.setRightTextVisibility(View.GONE);
            baseTitleBar.setRightImageVisibility(View.VISIBLE);
            baseTitleBar.setRightImageResource(context.getResources().getDrawable(R.drawable.hole_more));
            CommonUtils.switchMode(linearLayout, false);
        } else if (Constants.PRESENT_VALUE_FLAG.LIST.equals(mode)) {
            baseTitleBar.setRightImageVisibility(View.VISIBLE);
        }
        if (callBackInterface1 != null) {
            baseTitleBar.setLeftLayoutClickListener(callBackInterface1);
        }
        if (callBackInterface2 != null) {
            baseTitleBar.setRightLayoutClickListener(callBackInterface2);
        }
    }

    /**
     * 校验对象的所有属性是否为null
     *
     * @param exceptFields 除外的字段(传值时,该字段有值也会判定为null)
     */
    public static boolean checkObjFieldIsNull(Object obj, List<String> exceptFields) {
        try {
            for (Field field : obj.getClass().getDeclaredFields()) {
                field.setAccessible(true);
                if ((ListUtil.isEmpty(exceptFields) && field.get(obj) != null)
                        || (ListUtil.isNotEmpty(exceptFields) && !exceptFields.contains(field.getName()) && field.get(obj) != null)
                ) {
                    return false;
                }
            }
            return true;
        } catch (IllegalAccessException e) {
            LogUtil.e("checkObjFieldIsNull", "对象属性私有");
            return true;
        }
    }

    public static <T extends Activity & BindEditTextViewValue> void checkBack(T activity, Object obj, CallBackInterface callBackInterface) {
        activity.setObjValue();
        boolean needPrompt = activity.checkLinkedDataAndFiles();
        if (needPrompt) {
            final CommonDialog commonDialog = new CommonDialog(activity);
            commonDialog.setTitle(activity.getResources().getString(R.string.confirm_hint));
            commonDialog.setContent(activity.getResources().getString(R.string.return_hint));
            commonDialog.setCancel("不保存");
            commonDialog.setEnsure("保存");
            commonDialog.setOnEnsureClickListener(view -> {
                commonDialog.dismiss();
                callBackInterface.customizedFun();
            });
            commonDialog.setOnCancelClickListener((view) -> {
                activity.finish();
                commonDialog.dismiss();
            });
            commonDialog.show();
        } else {
            activity.finish();
        }
    }

    public static <T extends Activity & BindEditTextViewValue> void showIsSave(T activity, CallBackInterface callBackInterface) {
        boolean needPrompt = activity.checkLinkedDataAndFiles();
        if (needPrompt) {
            final CommonDialog commonDialog = new CommonDialog(activity);
            commonDialog.setTitle(activity.getResources().getString(R.string.confirm_hint));
            commonDialog.setContent(activity.getResources().getString(R.string.return_hint));
            commonDialog.setCancel("不保存");
            commonDialog.setEnsure("保存");
            commonDialog.setOnEnsureClickListener(view -> {
                commonDialog.dismiss();
                callBackInterface.customizedFun();
            });
            commonDialog.setOnCancelClickListener((view) -> {
                activity.finish();
                commonDialog.dismiss();
            });
            commonDialog.show();
        } else {
            activity.finish();
        }
    }

    /**
     * 弹出双按钮弹框
     */
    public static void showIsSave(Context context, CallBackInterface callBackInterface) {
        final CommonDialog commonDialog = new CommonDialog(context);
        commonDialog.setTitle(context.getResources().getString(R.string.confirm_hint));
        commonDialog.setContent(context.getResources().getString(R.string.return_hint));
        commonDialog.setOnEnsureClickListener(view -> {
            commonDialog.dismiss();
            callBackInterface.customizedFun();
        });
        commonDialog.setOnCancelClickListener(view -> commonDialog.dismiss());
        commonDialog.show();
    }

    /**
     * 检查BigDecimal是否为整数值
     * @param bd 传入的对象
     * @return true:整数
     */
    public static boolean isIntegerValue(BigDecimal bd) {
        if (bd == null) return false;
        return bd.signum() == 0 || bd.scale() <= 0 || bd.stripTrailingZeros().scale() <= 0;
    }

    /**
     * 将List转为String通过","拼接
     * @param list 需要转换的list
     * @return 转换后的的字符串
     */
    public static String listToStringCommaSplicing(List<?> list) {
        if (CollectionUtils.isEmpty(list)) {
            return "";
        }
        StringBuilder name = new StringBuilder();
        for (Object o : list) {
            name.append(",").append(o.toString());
        }
        return name.toString().replaceFirst(",", "");
    }

    /**
     * 判断图片格式
     * @param type 文件后缀
     * @return
     */
    public static boolean isPicture(String type){
        return ".jpg".equals(type) || ".png".equals(type) || ".jpeg".equals(type) || ".bmp".equals(type) || ".gif".equals(type);
    }

    /**
     * 判断视频格式
     * @param type 文件后缀
     * @return
     */
    public static boolean isVideo(String type){
        return ".mp4".equals(type) || ".mkv".equals(type) || ".wmv".equals(type) || ".avi".equals(type) || ".3gp".equals(type) || ".flv".equals(type) || ".mov".equals(type);
    }
}